package com.ygy.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {

    /**
     * 将字符串转换为MD5散列值
     * @param input 需要加密的字符串
     * @return MD5加密后的字符串
     */
    public static String getMD5String(String input) {
        try {
            // 创建MessageDigest对象，用于生成摘要
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 将需要加密的字符串转换为字节数组
            byte[] messageDigestData = input.getBytes();

            // 执行消息摘要计算
            byte[] digest = md.digest(messageDigestData);

            // 将得到的字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            // 返回MD5加密后的字符串
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to generate MD5 hash.", e);
        }
    }
}

/*// 使用示例
public class Main {
    public static void main(String[] args) {
        String newPwd = "your_password";
        String encryptedPwd = Md5Util.getMD5String(newPwd);
        System.out.println("Encrypted Password: " + encryptedPwd);
    }
}*/
